//
//  ZYComposeViewController.swift
//  CZ29WeiboZYH
//
//  Created by 沐颜澈 on 16/7/3.
//  Copyright © 2016年 muyanche. All rights reserved.
//

import UIKit

class ZYComposeViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
    }
    
    //MARK: - 设置UI
    private func setupUI() {
        
        view.backgroundColor = UIColor.lightGrayColor()
        setupNav()
        //添加控件
        view.addSubview(composeTextView)
        
        //添加控件
        view.addSubview(composeToolbar)
        composeTextView.addSubview(pictureView)
        
        //添加约束
        composeTextView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
            
        }
        
        //给底部的toolBar添加约束
        composeToolbar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
            
        }
        
        //pictureView的约束
        pictureView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(composeTextView).offset(10)
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            
            
        }
        
        //弹出一个相册
        pictureView.composePictureViewClosure = {[weak self] in
            
            self?.selectImages()
            
        }
        
        // 监听composeToolbar 中的按钮店家
        composeToolbar.closure = {[weak self] (type: CZComposeToolbarType) ->() in
            switch type{
            case .Picture:
                self?.selectImages()
                print("图片")
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("表情")
                //7.4
                self?.swithKeyboard()
                
            case .Add:
                print("+")
                
            }
            
        }
        
        // 通过系统通知监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        //7.7 接收表情键盘删除按钮的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteBtnClick", name: EmotionDeleteNoti, object: nil)
        
        //7.7 接收表情键盘按钮的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emotionButtonClick:", name: EmotionButtonNoti, object: nil)

        
    
    }
    //======================================================7.7===========
    func emotionButtonClick(noti: NSNotification) {
    
        guard let emotion = noti.object as? ZYEmotionModel else {

            return
        }
        
        if emotion.isEmoji {
        
            composeTextView.insertText(((emotion.code ?? "") as NSString).emoji())
            
        } else {
        
            //记录composeTextView上一次的富文本的记录
            let oldAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
            //设置图片表情
            //需要一个文本附件,自定义的文本附件
            
            let att = ZYTextAttachment()
            
            //设置emotion
            att.emotion = emotion
            
            let path = emotion.path ?? ""
            let png = emotion.png ?? ""
            let name = path + png
           
            //设置image
            att.image = UIImage(named:name , inBundle:  ZYEmotionTools.sharedTools.emotionBundle, compatibleWithTraitCollection: nil)
            
            //设置bounds
            let lineHeight = composeTextView.font!.lineHeight
            
            att.bounds = CGRect(x: 0, y: -4, width:lineHeight, height: lineHeight)
            
            //创建一个不可变的富文本
            let attr = NSAttributedString(attachment: att)
            
            //02.获取选中的光标
            let selectRange = composeTextView.selectedRange
            
            //01--拼接的方式不可取
            //oldAttr.appendAttributedString(attr)
            
            //02插入的方式不可取
           // oldAttr.insertAttributedString(attr, atIndex: selectRange.location)
            
            //03:替换
            oldAttr.replaceCharactersInRange(selectRange, withAttributedString: attr)
            
            //设置富文本的font
            oldAttr.addAttributes([NSFontAttributeName: composeTextView.font!], range: NSRange(location: 0, length: oldAttr.length))
            
            composeTextView.attributedText = oldAttr
            composeTextView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            
            //发送一个通知,隐藏或者显示占位的文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            //调用代理方法使右侧的按钮状态发生改变
            composeTextView.delegate?.textViewDidChange!(composeTextView)
            
        }
      
    }
    
    //删除按钮的点击事件
    func deleteBtnClick() {
        //print("删除的按钮点击啦")
        
        composeTextView.deleteBackward()
    }
    
    
    //监听键盘frame的改变
    func keyboardWillChangeFrame(noti:NSNotification) {
        
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        //更新toolBar的约束
        composeToolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
            
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            //更新布局
            self.view.layoutIfNeeded()
        }
        
    }
    

    
    //移除通知
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
    //MARK: - 设置导航控制器
    func setupNav() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancleClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendClick")
        
        //设置右侧的按钮默认是不能点击的
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置titleView
        navigationItem.titleView = titleView
        
    }
    
    //MARK: - 取消按钮的点击方法
    @objc private func cancleClick() {
        
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(false, completion: nil)
    
    }
    
    //MARK: - 发送按钮的点击事件
    @objc private func sendClick() {
        /*
            发送服务器:显示在我们的app或者pc端,显示A表情a
        
        
        */
       // print("发送微博")
        /*
            1.遍历的结果
            2.遍历的范围
            3.是否停止遍历
        
        */
        
        //定义一个空的字符串
        var resultStr = ""
        
        composeTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (dict, range, _) -> Void in
            
            //print("结果:\(dict)范围\(range)")
            //如果是文本附件
            if let att = dict["NSAttachment"] as? ZYTextAttachment {
            
                //print("结果:\(dict)范围\(range)")
                print( att.emotion?.chs)
                
                resultStr += (att.emotion?.chs ?? "")
                
            } else {
                //如果是A的话就将文字记录下来
                let name = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                
                resultStr += name
                
            }
            
            
        }
        //print(resultStr)
        
        //如果配图中的数组的数量大于0就代表发送有图片的微博
        if pictureView.imageList.count > 0 {
        
            upload(resultStr)
        } else {
            update(resultStr)
        
        }
        
    }
    
    //懒加载控件
    private lazy var titleView: UILabel = {
        
        let name = ZYUserAccountTools.sharedTools.userAccount?.screen_name ?? ""
        
        //最终显示的文字
        let str = "发微博\n\(name)"
        //获取range
        let range = (str as NSString).rangeOfString(name)
        
        //使用富文本
        let attr = NSMutableAttributedString(string: str)
        
        //设置富文本
        attr.addAttributes([NSForegroundColorAttributeName:ThemeColor, NSFontAttributeName:UIFont.systemFontOfSize(11)], range: range)
        let lab = UILabel()
        lab.attributedText = attr
        lab.textAlignment = .Center
        
       
        lab.numberOfLines = 0
        //这句话一定要记得写在最下面
        //否则自己的名字会显示不出
         lab.sizeToFit()
        return lab
    
    }()
    
    //MRAK: - 懒加载控件
    private lazy var composeTextView: ZYComposeTextView = {
    
        let view = ZYComposeTextView()
        
        view.placeHolder = "人生得意须尽欢..."
        
        view.delegate = self
        //允许view上下拖动
        view.alwaysBounceVertical = true
        view.font = UIFont.systemFontOfSize(18)
        
        return view
        
    
    }()
    
    //懒加载底部的toolBar
    private lazy var composeToolbar: ZYComposeToolbar = ZYComposeToolbar()
    //懒加载配图
    private lazy var pictureView: ZYComposePictureView = ZYComposePictureView()
    
    //----------自定义表情键盘-----------------7.4
    private lazy var keyBoardView: ZYEmotionKeyboard = {
        let view = ZYEmotionKeyboard()
        view.frame = CGRect(x: 0, y: 0, width: SCREENW, height: 216)
        
        return view
        
    }()
    
    
    
}

//----------------------------------------7.4 处理表情键盘
//处理tooBar按钮的点击事件
extension ZYComposeViewController {
    func selectImages() {
        let picker = UIImagePickerController()
        
        //设置代理
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
        
    
    }
    
    //MARK: - 切换键盘
    func swithKeyboard() {
        /*
        如何判断当前显示的是系统的键盘还是自定义的键盘
        如果是系统键盘, 自定义inputView是nil的话就切换成自定义键盘
        否则就代表自定义键盘,切换成系统的键盘
        如果
        */
        if composeTextView.inputView == nil {
            //切换成自定义键盘
            //composeTextView.inputView = UIButton(type:UIButtonType.ContactAdd)
            composeTextView.inputView = keyBoardView
            composeToolbar.isEmotion = true
        
        } else { 
            //代表的是自定义键盘
            composeTextView.inputView = nil
            
            composeToolbar.isEmotion = false
        }
        
        //记得刷新inputView
        composeTextView.reloadInputViews()
        //使其成为第一响应者
        composeTextView.becomeFirstResponder()
        
        
    }
    
}

//MARK: - 代理方法的实现
extension ZYComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //方式2
        let data1 = UIImageJPEGRepresentation(image, 0.2)
        
        //let data = UIImagePNGRepresentation(scaleImageOfWidth(600, image: image))
        data1?.writeToFile("users/muyanche/Desktop/呵呵.png", atomically: true)
        
        print(image)
       // composeTextView.backgroundColor = UIColor(patternImage: image)
        
        //图片填充
       // pictureView.addImages(image)
        pictureView.addImages(scaleImageOfWidth(600, image: image))
        //自己关闭控制器
        picker.dismissViewControllerAnimated(false, completion: nil)
        
    }
    
    
    //MARK: - 压缩图片 7.4
    func scaleImageOfWidth(width:CGFloat,image:UIImage) ->UIImage {
    
        if width > image.size.width {
        
            return image
        }
        //否则及等比例计算出图片的高度
        let height = (width * image.size.width) / (image.size.width)
        //创建一个rect
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        
        //1.开启上下文读对象
        UIGraphicsBeginImageContext(rect.size)
        //2.将image渲染到上下文
        image.drawInRect(rect)
        //3获取上下文的结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        
        //4关闭上下文
        UIGraphicsEndImageContext()
        return result
        
    }
    

}

//MARK: - 发送微博的请求
extension ZYComposeViewController{
    //MARK: - 发送文字微博
    func update(status: String) {
        ZYNetworkTools.sharedNetworkTools.composeupdate(status, success: { (response) -> () in
              print("发送成功")
            
            }) { (error) -> () in
                print("发送失败")

        }
    
    }
    
    //MARK: - 7.4 发送有图片的微博
    func upload(status: String) {
        
        ZYNetworkTools.sharedNetworkTools.composeUpload(status, imageList: pictureView.imageList, success: { (response) -> () in
                 print("发送成功")
            }) { (error) -> () in
                print("发送失败")
        }
        
    }
    
    func demo1() {
        //请求url
        let URLString = "https://upload.api.weibo.com/2/statuses/upload.json"
        //请求的参数
        let params = [
            "access_token": ZYUserAccountTools.sharedTools.accessToken!,
            "status":composeTextView.text
            
        ]
        
        //MARK: - 发送请求
        ZYNetworkTools.sharedNetworkTools.POST(URLString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
            
            //遍历数组
            /*
            以表单的形式提交(拼接到表单的后面提交)
            data:将要上传到服务器的二进制文件
            name:服务器要求规定好的文件的名称
            fileName:随便写.上传完成之后保存到服务器的文件路径
            mimeType:指定上传的二进制文件的格式,application/octet-stream 忽略上传文件的格式
            */
            
            for image in self.pictureView.imageList {
                //image转二进制
                let data = UIImagePNGRepresentation(image)!
                formdata.appendPartWithFileData(data, name: "pic", fileName: "zhu", mimeType: "application/octet-stream")

            }
            
            
            }, progress: nil, success: { (_, response) -> Void in
                print("发送成功")
            }) { (_, error) -> Void in
                print("发送失败")
        }

        
    }
}

//MARK : - 实现代理方法
extension ZYComposeViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
        
    }

}



































